<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/22
 * Time: 16:25
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\log\Log;
use app\common\library\Weixin;
use think\Db;

class Notify extends Api {
	
	protected $noNeedLogin = '*';
	
	/**
	 * 支付回调
	 */
	public function order() {
		$path = 'notify'.DS;
		$res = Weixin::notify($path);
//		$res = json_decode('{"appid":"wx8baa81690abfc1a9","attach":"order","bank_type":"ICBC_CREDIT","cash_fee":"100","fee_type":"CNY","is_subscribe":"Y","mch_id":"1556575171","nonce_str":"9lcpcg4dap1ndpl7g194klp71aiu0v7e","openid":"oyVO31JNY2ocXSjLJ8qhXUhYfLg8","out_trade_no":"8-1569128643","result_code":"SUCCESS","return_code":"SUCCESS","sign":"C84A8CF1FCB74BFBD4A60A145373F4EA","time_end":"20190922130409","total_fee":"100","trade_type":"JSAPI","transaction_id":"4200000389201909220856298484"}', true);
		if($res) {
			$arr = explode('-', $res['out_trade_no']);
			$orderId = $arr[0];
			$model = new \app\common\model\Order();
			$orderRes = $model->paySuccess($orderId, $res['transaction_id']);
			if($orderRes) {
				Log::info('支付回调操作成功'.PHP_EOL, $path);
				$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
				echo $xml;
				die;
			} else {
				Log::info('支付回调操作失败'.PHP_EOL, $path);
			}
		}
	}
	
	/**
	 * 支付回调
	 */
	public function promotion() {
		$path = 'notify'.DS;
		$res = Weixin::notify($path);
//		$res = json_decode('{"appid":"wx7c9db69cf3d03426","attach":"order","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1568006781","nonce_str":"e1kpwm6tadfuxr6jbnqislvtzgy5fwqe","openid":"o-XL25TgTLU-7PBhHMXAY8R98ff4","out_trade_no":"263-1577269057","result_code":"SUCCESS","return_code":"SUCCESS","sign":"DFDA146249D1FB3AD5D248F5F5399BCA","time_end":"20191225181749","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000458201912253721375001"}', true);
		if($res) {
			$arr = explode('-', $res['out_trade_no']);
			$orderId = $arr[0];
			$model = new \app\common\model\AgentOrder();
			$orderRes = $model->paySuccess($orderId, $res['transaction_id']);
			if($orderRes) {
				Log::info('代理权限支付回调操作成功'.PHP_EOL, $path);
				$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
				echo $xml;
				die;
			} else {
				Log::info('代理权限支付回调操作失败【'.$model->getError().'】'.PHP_EOL, $path);
			}
		}
	}
	
	
	/**
	 * 微信退款回调
	 */
	public function wxRefund(){
		header('Content-type:text/html;charset=utf8');
		$path = 'notify'.DS.'refund'.DS;
		$log = new \app\common\library\log\Log();
		$log::info('==================='.date('Y-m-d H:i:s') . "==============\r\n", $path);
		

		$xml = isset($GLOBALS['HTTP_RAW_POST_DATA'])?$GLOBALS['HTTP_RAW_POST_DATA']:file_get_contents('php://input', 'r');
		$xmlObj = simplexml_load_string($xml, 'SimplexmlElement', LIBXML_NOCDATA);
		$log::info(json_encode($xmlObj) . "\r\n", $path);
		$data = json_decode(json_encode($xmlObj), true);
		
		$key = config('weixin.pay_key');
		
		$result = openssl_decrypt(base64_decode($data['req_info']), 'aes-256-ecb', strtolower(md5($key)), OPENSSL_RAW_DATA);
		$arr = Weixin::xmlToArray($result);
		
		if(isset($data['return_code']) && $data['return_code'] == 'SUCCESS' && isset($arr['refund_status']) && $arr['refund_status'] == 'SUCCESS') {
			$orderRes = Db::name('order')->where(['transaction_no' => $arr['transaction_id']])
				->update(['pay_status' => \app\common\model\Order::PAY_STATUS_REFUND]);
			
			if($orderRes !== false) {
				$log::info('退款回调操作成功'.PHP_EOL, $path);
				$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
				echo $xml;
				die;
			} else {
				$log::info('退款回调操作失败'.PHP_EOL, $path);
			}
		} else {
			$log::info('解密数据出错'.PHP_EOL, $path);
		}
		
	}
}